﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Common
{
    /// <summary>
    /// 常用的方法
    /// </summary>
    public static class Tools
    {

        /// <summary>
        /// 获取字符串的长度,汉字占两个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int getStrLength(string str)
        {
            return Encoding.UTF8.GetByteCount(str);
        }

        /// <summary>
        /// 验证邮箱格式是否正确,正确的格式为 true
        /// </summary>
        /// <param name="email">电子邮箱字符串</param>
        /// <returns>返回值为 true 通过验证</returns>
        public static bool IsEmail(string email)
        {
            Regex r = new Regex("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$");

            if (r.IsMatch(email))
            {
                return true;
            }
            return false;
        }


        /// <summary>
        /// 获取一个随机字符串
        /// </summary>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string getRandomStr(int len=8)
        {
            string s = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm7410852963.";
            StringBuilder sb = new StringBuilder();
            Random r = new Random();
            for (int i = 0; i < len; i++)
            {
                sb.Append(s[r.Next(s.Length)]);
            }
            return sb.ToString();
        }


        /// <summary>  
        /// 扩展方法, 获取客户端的真正ip  
        /// </summary>  
        /// <returns></returns>  
        public static string GetRealIP(this HttpContext context)
        {
            string result = String.Empty;
            result = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();

            if (string.IsNullOrWhiteSpace(result))
            {
                result = context.Connection.RemoteIpAddress.ToString();
            }

            if (string.IsNullOrWhiteSpace(result))
            {
                result = string.Empty;
            }
            return result;
        }

        /// <summary>
        /// 判断是否为ip地址
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static bool IsIPAddress(string str)
        {
            if (string.IsNullOrWhiteSpace(str) || str.Length < 7 || str.Length > 15)
                return false;

            string regformat = @"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);

            return regex.IsMatch(str);
        }
    }
}
